package com.repair.dao.Person.impl;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.hibernate.Transaction;


import com.repair.dao.Person.IPersonDao;
import com.repair.domain.Person;
import com.repair.factory.HibernateSessionFactory;

public class PersonDao implements IPersonDao {

	@Override
	public void savePerson(Person obj) {
		Session session = HibernateSessionFactory.getSession();

		try {
			Transaction tx = session.beginTransaction();
			if (session != null) {
				session.saveOrUpdate(obj);
				tx.commit();
				session.flush();
				session.clear();
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (session != null) {
				session.flush();
				session.clear();
			}
		}
	}

	@Override
	@SuppressWarnings("unchecked")
	public List<Person> getAllPerson() {
		List<Person> list = new ArrayList<Person>();
		Session session = HibernateSessionFactory.getSession();
		try {
			if (session != null) {
				String sql = "select * from PERSON";
				SQLQuery query = session.createSQLQuery(sql);
				list = query.addEntity(Person.class).list();
			}
		} catch (Exception e) {

		} finally {
			if (session != null) {
				session.flush();
				session.clear();
			}
		}
		return list;

	}

	@Override
	public void deletePerson(Person obj) {
		Session session = HibernateSessionFactory.getSession();
		try {
			Transaction tx = session.beginTransaction();
			if (session != null) {
				 session.delete(obj);
				tx.commit();
			}
		} catch (Exception e) {

		} finally {
			if (session != null) {
				session.flush();
				session.clear();
			}
		}

	}
}
